package com.zgw.his.design.resource;

import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.eclipse.core.internal.resources.Workspace;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceChangeEvent;
import org.eclipse.core.resources.IResourceChangeListener;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.Path;
import org.eclipse.wb.internal.core.utils.IOUtils2;

import com.zgw.his.common.ValueUtil;
import com.zgw.his.design.common.LocalResourceHelp;
import com.zgw.his.design.model.MedicalResource;
import com.zgw.his.design.model.Folder;
import com.zgw.his.design.model.Template;
import com.zgw.his.server.emr.IEmrService;
import com.zgw.his.server.emr.entity.Temrtemplate;
import com.zgw.his.server.emr.entity.Temrtemplatesort;
import com.zgw.his.server.exceptions.BusinessException;
import com.zgw.his.server.util.SpringBeanFactory;

/**
 * <b>资源管理工具</b>
 * <p/>
 * 用于更新、读取、创建模板资源 </br>
 * */
@SuppressWarnings({ "restriction", "static-access" })
public class MedicalResourceManager {
	// 资源根路径 RESOURCE ROOT PATH
	public final static String RRP = "/templates/src";

	// 默认模版路径 DEFAULT TEMPLATE PATH
	private static String DTP = "/templates/DEFAULT.xwt";

	private static Workspace workspace;
	private String workspacePath; // 工作空间目录

	private List<Folder> rootFolders = new ArrayList<Folder>(); // 根目录
	private Folder defaultFolder; // 缺省目录

	private LocalResoureceManager localManager = new LocalResoureceManager();

	// ==============================================
	// 模版库管理
	// ==============================================
	private Map<String, Temrtemplate> temrtemplates; // 病历模版库
	private Map<String, Temrtemplatesort> temrtemplatesorts; // 病历模版库类别
	private IEmrService emrService = (IEmrService) SpringBeanFactory
			.getServiceBean(IEmrService.class);

	public MedicalResourceManager() {
		try {
			LocalResourceHelp.WORKSPACE.build(
					IncrementalProjectBuilder.CLEAN_BUILD, null);
		} catch (CoreException e) {
			e.printStackTrace();
		}
	}

	public Folder newFolder(Folder parent, String name) throws Exception {
		Temrtemplatesort sort = new Temrtemplatesort();
		sort.setFname(name);
		sort.setFparent(parent != null ? parent.getNumber() : null);

		Folder f = newFolder(sort);

		sort.setFpath(f.getPath());
		sort.setFnumber(f.getNumber());
		f.setData(sort);
		return f;
	}

	public Template newTemplate(Folder parent, String name) throws Exception {
		Temrtemplate temp = new Temrtemplate();
		temp.setFname(name);
		temp.setFsort(parent != null ? parent.getNumber() : null);

		Template t = newTemplate(temp, getDefaultTemplateContent());
		temp.setFpath(t.getPath());
		temp.setFnumber(t.getNumber());
		temp.setFversion(-1L);
		if (t.getFolder() != null && !isDefaultFolder(t.getFolder()))
			temp.setFsort(t.getFolder().getNumber());
		t.setData(temp);
		return t;

	}

	// 删除目录
	public void deleteFolder(Folder folder) throws Exception {
		List deletes = new ArrayList();
		for (Folder fo : folder.findFolderAll()) {
			if (fo.getData() instanceof Temrtemplatesort)
				deletes.add(fo.getData());
		}
		for (Template t : folder.findTemplateAll()) {
			if (t.getData() instanceof Temrtemplate)
				deletes.add(t.getData());
		}
		localManager.deleteFolder(folder); // 删除本地资源

		emrService.deleteAll(deletes); // 删除
	}

	// 删除模板
	public void deleteTemplate(Template temp) throws Exception {
		localManager.deleteTemplate(temp);
		if (temp.getData() instanceof Temrtemplate)
			emrService.delete(temp.getData());
	}

	public void save() throws Exception {
		List<Temrtemplatesort> sorts = new ArrayList<Temrtemplatesort>();
		List<Temrtemplate> temps = new ArrayList<Temrtemplate>();
		Temrtemplatesort sort;

		for (Folder f : localManager.getFolders()) {
			if (!isDefaultFolder(f) && f.getState() == Folder.STATE_NEW) {
				sort = new Temrtemplatesort();
				sort.setFnumber(f.getNumber());
				sort.setFname(f.getName());
				sort.setFpath(f.getPath());
				if (f.getParent() != null && !isDefaultFolder(f.getParent()))
					sort.setFparent(f.getParent().getNumber());
				sorts.add(sort);
			}
		}
		Temrtemplate temp;

		for (Template t : localManager.getTemplates()) {
			if (t.getState() == Template.STATE_NEW) {
				temp = (Temrtemplate) (t.getData() == null ? new Temrtemplate()
						: t.getData());
				temp.setFname(t.getName());
				temp.setFpath(t.getPath());
				temp.setFnumber(t.getNumber());
				temp.setFversion(1L);
				temp.setFcreatetime(new Date());
				temp.setFcontent(getTemplateContent(t));
				if (t.getFolder() != null && !isDefaultFolder(t.getFolder()))
					temp.setFsort(t.getFolder().getNumber());

				temps.add(temp);
			} else if (t.getState() == Template.STATE_UPDATE
					&& t.getData() instanceof Temrtemplate) {
				temp = (Temrtemplate) t.getData();
				temp.setFcontent(getTemplateContent(t));
				temp.setFversion(temp.getFversion() + 1);
				temps.add(temp);
			}
		}
		List saveList = new ArrayList();
		saveList.addAll(temps);
		saveList.addAll(sorts);
		emrService.saveOrUpdateAll(saveList);
		saveAfter(saveList);
	}

	/**
	 * 将本地模版，与模版库同步
	 * 
	 * @throws Exception
	 * */
	public void synchronization() throws Exception {
		// --------------
		// 加载基础静态数据
		// --------------
		BaseResource.loadElement();
		BaseResource.loadInput();
		// --------------
		// 加载库版库
		// --------------
		loadTemplateLib();

		// ----------------------------------------------
		// 加载本地资源
		// ----------------------------------------------
		localManager.loadLocal();

		// --------------
		// 同步目录　
		// --------------
		Folder folder;
		for (Temrtemplatesort sort : temrtemplatesorts.values()) {
			folder = localManager.getFolder(sort.getFnumber());
			if (folder == null) {
				folder = newFolder(sort);
			}
			folder.setNumber(sort.getFnumber());
			folder.setState(Folder.STATE_NOMAL);
			localManager.persistent(folder);
			folder.setData(sort);
		}

		for (Folder f : localManager.getFolders()) { // 删除
			if (f.getData() == null && !isDefaultFolder(f)) {
				if (f.getState() == Folder.STATE_NOMAL) {
					localManager.deleteFolder(f);
				} else {
					Temrtemplatesort sort = new Temrtemplatesort(f.getNumber());
					sort.setFparent(f.getParent() != null ? f.getParent()
							.getNumber() : null);
					sort.setFpath(f.getPath());
					f.setData(sort);
					f.setState(Folder.STATE_NEW);
					localManager.persistent(f);
				}
			}
		}

		// --------------
		// 同步模版　
		// --------------
		Template template;
		for (Temrtemplate temp : temrtemplates.values()) {
			template = localManager.getTemplate(temp.getFnumber());
			if (template != null) {
				if (temp.getFversion() == null
						|| !temp.getFversion().toString() // 检测版本号为空，或者不相等
								.equals(template.getVersion())) {
					IOUtils2.setFileContents((IFile) template.getResource(),
							temp.getFcontent());
					template.setState(Template.STATE_NOMAL);
				}
			} else {
				template = newTemplate(temp, temp.getFcontent());
				template.setState(Template.STATE_NOMAL);
			}

			template.setNumber(temp.getFnumber());
			template.setVersion(temp.getFversion().toString());
			template.setData(temp);
			localManager.persistent(template);
		}

		for (Template t : localManager.getTemplates()) {
			if (t.getData() == null) {
				if (t.getState() != Template.STATE_NEW) {// 删除
					localManager.deleteTemplate(t);
				} else {
					Temrtemplate temp = new Temrtemplate();
					temp.setFname(t.getName());
					temp.setFpath(t.getPath());
					temp.setFnumber(t.getNumber());
					temp.setFversion(-1L);
					if (t.getFolder() != null
							&& !isDefaultFolder(t.getFolder()))
						temp.setFsort(t.getFolder().getNumber());
					t.setData(temp);
					t.setState(Template.STATE_NEW);
					localManager.persistent(t);
				}
			}
		}

	}

	private Template newTemplate(Temrtemplate temp, String content)
			throws Exception {
		Folder parent = null;
		if (ValueUtil.hasValue(temp.getFsort())) {
			parent = localManager.getFolder(temp.getFsort());
			if (parent == null) {
				parent = newFolder(this.temrtemplatesorts.get(temp.getFsort()));
			}
		}
		Template template = localManager.createTemplate(parent,
				temp.getFname(), temp.getFnumber(), content);
		return template;
	}

	private Folder newFolder(Temrtemplatesort sort) throws Exception {
		Folder parent = null;
		if (ValueUtil.hasValue(sort.getFparent())) {
			parent = localManager.getFolder(sort.getFparent());
			if (parent == null) {
				parent = newFolder(this.temrtemplatesorts
						.get(sort.getFparent()));
			}
		}
		Folder folder = localManager.createFolder(parent, sort.getFname());
		if (sort.getFnumber() != null) {
			localManager.modifyNumber(folder, sort.getFnumber());
		}
		return folder;
	}

	private void saveAfter(List saveList) throws CoreException {
		for (Object obj : saveList) {
			if (obj instanceof Temrtemplatesort) {
				Folder f = localManager.getFolder(((Temrtemplatesort) obj)
						.getFnumber());
				f.setState(Folder.STATE_NOMAL);
				localManager.persistent(f);
				f.setData(obj);
			} else if (obj instanceof Temrtemplate) {
				Template t = localManager.getTemplate(((Temrtemplate) obj)
						.getFnumber());
				t.setVersion(((Temrtemplate) obj).getFversion() + "");
				t.setState(Template.STATE_NOMAL);
				localManager.persistent(t);
				t.setData(obj);
			}
		}
	}

	/**
	 * 获得所有目录
	 * */
	public Folder[] getFolders() {
		return localManager.getFolders();
	}

	// 获得默认 母板 内容
	private String getDefaultTemplateContent() throws IOException {
		String content = "";
		try {
			content = IOUtils2.readString(LocalResourceHelp.getFile(DTP)
					.getContents());
		} catch (Exception e) {
			e.printStackTrace();
		}
		return content;
	}

	/**
	 * 加载远程模版库
	 * 
	 * @throws BusinessException
	 * */
	public void loadTemplateLib() throws BusinessException {
		List<Temrtemplate> listTemp = emrService
				.getAllEntity(Temrtemplate.class);
		temrtemplates = new HashMap<String, Temrtemplate>();
		for (Temrtemplate t : listTemp) {
			this.temrtemplates.put(t.getFnumber(), t);
		}
		List<Temrtemplatesort> listSorts = emrService
				.getAllEntity(Temrtemplatesort.class);
		temrtemplatesorts = new HashMap<String, Temrtemplatesort>();
		for (Temrtemplatesort s : listSorts) {
			this.temrtemplatesorts.put(s.getFnumber(), s);
		}
	}

	public Workspace getWorkspace() {
		return workspace;
	}

	/**
	 * 修改模版属性
	 * */
	public void modifyInfo(Template template, boolean submit) throws Exception {
		Temrtemplate temrtemplate = (Temrtemplate) template.getData();
		if (submit) { // 是否提交至数据库
			if (!ValueUtil.hasValue(temrtemplate.getFid()))
				throw new Exception("模版未提交");
			emrService.saveOrUpdate(temrtemplate); // 保存模版库中信息
		}
		if (!template.getNumber().equals(temrtemplate.getFnumber())) {
			localManager.modifyNumber(template, temrtemplate.getFnumber());
		}
		if (!template.getName().equals(temrtemplate.getFname())) {
			// 重命名文件
			localManager.rename(template, temrtemplate.getFname());
		}
	}

	/**
	 * 是否为缺省目录
	 * */
	public boolean isDefaultFolder(Folder folder) {
		return localManager.isDefaultFolder(folder);
	}

	public String getTemplateContent(Template temp) throws Exception {
		String content = IOUtils2.readString(((IFile) temp.getResource())
				.getContents());
		// content = new String(content.getBytes(), "UTF-8");
		return content;
	}

	public Folder[] getRootFolders() {
		return localManager.getRootFolders();
	}

}
